package com.jiangcheng.demo.service.impl;

import com.jiangcheng.demo.entity.Comment;
import com.jiangcheng.demo.mapper.CommentMapper;
import com.jiangcheng.demo.mapper.ReplyMapper;
import com.jiangcheng.demo.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangcheng.demo.service.ReplyService;
import com.jiangcheng.demo.utils.FindCommentsVo;
import com.jiangcheng.demo.utils.LikedVo;
import com.jiangcheng.demo.utils.NewResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-07-26
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    CommentMapper commentMapper;
    @Resource
    ReplyService replyService;
    @Autowired
    LikedServiceImpl likedService;


    @Override
    public NewResult findCommentsByArtId(int artId,int uId) {
        // 根据文章ID查询评论
        List<FindCommentsVo> findCommentsVos = commentMapper.findCommentsByArtId(artId);
        // 根据评论ID 查询回复的数量
        for (FindCommentsVo findCommentsVo: findCommentsVos){
            // 给每条评论装进点赞信息
            /**
             * 1 评论 2 文章 3 回复 4 树洞
             */
            LikedVo likeInfo = likedService.findLikeNumByObjId(findCommentsVo.getCId(), 1, uId);
            findCommentsVo.setLikeNum(likeInfo.getCount());
            findCommentsVo.setIsLike(likeInfo.getExists());
            int replyCount = replyService.findReplyCountByCommentId(findCommentsVo.getCId());
            findCommentsVo.setReplyCount(replyCount);
        }
        

        return new NewResult(200, true, "查询评论成功", findCommentsVos);
    }

    @Override
    public NewResult findCommentsByTreeId(int tId) {
        // 根据树洞ID查询评论
        List<FindCommentsVo> findCommentsVos = commentMapper.findCommentsByTreeId(tId);
        if (findCommentsVos.size() <= 0){
            return new NewResult(400, false, "暂无评论");
        }
        // 根据评论ID 查询回复的数量
        for (FindCommentsVo findCommentsVo: findCommentsVos){
            int replyCount = replyService.findReplyCountByCommentId(findCommentsVo.getCId());
            findCommentsVo.setReplyCount(replyCount);
        }


        return new NewResult(200, true, "查询评论成功", findCommentsVos);
    }

    @Override
    public NewResult insertComment(Comment comment) {
        int insert = commentMapper.insert(comment);
        if (insert < 1){
            return new NewResult(400, false, "网络错误");
        }
        return new NewResult(200, true, "评论成功");
    }


}
